from fastapi import HTTPException, status
from sqlalchemy import func, update
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import Session
from typing import List, Optional
from models.model import Permission
from .schemas import PermissionCreate, PermissionUpdate

class PermissionService:
    @staticmethod
    async def create_permission(db: Session, permission: PermissionCreate) -> Permission:
        """
        创建权限
        """
        try:
            # 检查唯一性约束
            if db.query(Permission).filter(Permission.en_name == permission.en_name).first():
                raise HTTPException(
                    status_code=status.HTTP_409_CONFLICT,
                    detail="Permission英文名称已存在"
                )

            if db.query(Permission).filter(Permission.name == permission.name).first():
                raise HTTPException(
                    status_code=status.HTTP_409_CONFLICT,
                    detail="Permission中文名称已存在"
                )

            db_permission = Permission(
                en_name=permission.en_name,
                name=permission.name,
                description=permission.description,
                type=permission.type,
                is_active=1
            )
            
            db.add(db_permission)
            db.commit()
            db.refresh(db_permission)
            return db_permission
        except IntegrityError as e:
            db.rollback()
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="数据完整性错误"
            )

    @staticmethod
    async def get_permission(db: Session, permission_id: int) -> Permission:
        """
        获取权限详情
        """
        permission = db.query(Permission).filter(
            Permission.id == permission_id,
            Permission.is_active == 1
        ).first()
        
        if not permission:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="权限不存在或已被删除"
            )
        return permission

    @staticmethod
    async def update_permission(
        db: Session, 
        permission_id: int,
        update_data: PermissionUpdate
    ) -> Permission:
        """
        更新权限信息
        """
        # 获取待更新权限
        permission = await PermissionService.get_permission(db, permission_id)
        
        try:
            # 检查名称唯一性
            if update_data.en_name and update_data.en_name != permission.en_name:
                if db.query(Permission).filter(
                    Permission.en_name == update_data.en_name,
                    Permission.id != permission_id
                ).first():
                    raise HTTPException(
                        status_code=status.HTTP_409_CONFLICT,
                        detail="英文名称已存在"
                    )

            if update_data.name and update_data.name != permission.name:
                if db.query(Permission).filter(
                    Permission.name == update_data.name,
                    Permission.id != permission_id
                ).first():
                    raise HTTPException(
                        status_code=status.HTTP_409_CONFLICT,
                        detail="中文名称已存在"
                    )

            # 动态更新字段
            update_dict = update_data.dict(exclude_unset=True)
            db.execute(
                update(Permission)
                .where(Permission.id == permission_id)
                .values(**update_dict)
            )
            db.commit()
            return await PermissionService.get_permission(db, permission_id)
        except IntegrityError:
            db.rollback()
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="更新操作导致数据冲突"
            )

    @staticmethod
    async def delete_permission(db: Session, permission_id: int) -> bool:
        """
        软删除权限（设置is_active=0）
        """
        permission = await PermissionService.get_permission(db, permission_id)
        try:
            db.execute(
                update(Permission)
                .where(Permission.id == permission_id)
                .values(is_active=0)
            )
            db.commit()
        except Exception as e:
            print(f"{str(e)}")
            db.rollback()
            raise e
        return True

    @staticmethod
    async def list_permissions(
        db: Session,
        skip: int = 0,
        limit: int = 100,
        include_inactive: bool = False
    ) -> List[Permission]:
        """
        分页获取权限列表
        """
        query = db.query(Permission)
        
        if not include_inactive:
            query = query.filter(Permission.is_active == 1)
            
        return query.order_by(Permission.created_time.desc()).offset(skip).limit(limit).all()

    @staticmethod
    async def search_permissions(
        db: Session,
        keyword: Optional[str] = None,
        perm_type: Optional[str] = None
    ) -> List[Permission]:
        """
        高级搜索接口
        """
        query = db.query(Permission).filter(Permission.is_active == 1)
        
        if keyword:
            search = f"%{keyword}%"
            query = query.filter(
                (Permission.en_name.ilike(search)) |
                (Permission.name.ilike(search)) |
                (Permission.description.ilike(search))
            )
            
        if perm_type:
            query = query.filter(Permission.type == perm_type)
            
        return query.order_by(Permission.created_time.desc()).all()